import * as chokidar from 'chokidar';
import * as path from 'path';
import { EventEmitter } from 'events';
import { ComponentParser } from '../parser/parser';

/**
 * 文件变更类型
 */
export enum FileChangeType {
  ADDED = 'added',
  CHANGED = 'changed',
  REMOVED = 'removed'
}

/**
 * 文件变更事件
 */
export interface FileChangeEvent {
  type: FileChangeType;
  path: string;
}

/**
 * 文件监控器
 */
export class FileWatcher extends EventEmitter {
  private watcher: chokidar.FSWatcher | null = null;
  private watchPaths: string[];
  private parser: ComponentParser;
  
  /**
   * 构造函数
   * @param watchPaths 要监控的路径
   * @param parser 组件解析器实例
   */
  constructor(watchPaths: string[], parser: ComponentParser) {
    super();
    this.watchPaths = watchPaths;
    this.parser = parser;
    console.log(`初始化文件监控器，监控路径: ${watchPaths.join(', ')}`);
  }
  
  /**
   * 开始监控
   */
  start(): void {
    if (this.watcher) {
      return;
    }
    
    // 将路径转为绝对路径
    const absolutePaths = this.watchPaths.map(p => 
      path.isAbsolute(p) ? p : path.resolve(process.cwd(), p)
    );
    
    console.log(`开始监控文件变更，路径: ${absolutePaths.join(', ')}`);
    
    // 创建监控器
    this.watcher = chokidar.watch(absolutePaths, {
      persistent: true,
      ignoreInitial: true,
      ignorePermissionErrors: true,
      awaitWriteFinish: {
        stabilityThreshold: 300,
        pollInterval: 100
      }
    });
    
    // 监听文件添加事件
    this.watcher.on('add', async (filePath) => {
      if (this.isVueFile(filePath)) {
        console.log(`文件添加: ${filePath}`);
        
        // 增量解析添加的文件
        await this.parser.parseComponentIncremental(filePath);
        
        // 发送文件变更事件
        this.emit('change', { 
          type: FileChangeType.ADDED, 
          path: filePath 
        } as FileChangeEvent);
      }
    });
    
    // 监听文件变更事件
    this.watcher.on('change', async (filePath) => {
      if (this.isVueFile(filePath)) {
        console.log(`文件变更: ${filePath}`);
        
        // 增量解析变更的文件
        await this.parser.parseComponentIncremental(filePath);
        
        // 发送文件变更事件
        this.emit('change', { 
          type: FileChangeType.CHANGED, 
          path: filePath 
        } as FileChangeEvent);
      }
    });
    
    // 监听文件删除事件
    this.watcher.on('unlink', async (filePath) => {
      if (this.isVueFile(filePath)) {
        console.log(`文件删除: ${filePath}`);
        
        // 增量解析删除的文件
        await this.parser.parseComponentIncremental(filePath);
        
        // 发送文件变更事件
        this.emit('change', { 
          type: FileChangeType.REMOVED, 
          path: filePath 
        } as FileChangeEvent);
      }
    });
    
    // 监听错误
    this.watcher.on('error', (error) => {
      console.error(`文件监控错误:`, error);
    });
  }
  
  /**
   * 停止监控
   */
  stop(): Promise<void> {
    if (!this.watcher) {
      return Promise.resolve();
    }
    
    console.log('停止文件监控');
    return this.watcher.close();
  }
  
  /**
   * 判断是否为Vue文件
   * @param filePath 文件路径
   */
  private isVueFile(filePath: string): boolean {
    return path.extname(filePath).toLowerCase() === '.vue' && 
           this.parser.isFileInScanPaths(filePath);
  }
} 